import { ElMessage, ElMessageBox, UploadRequestOptions } from 'element-plus'
import { useConfigStore } from '@renderer/stores'
import { VideoState } from '@renderer/types'

export default () => {
  const { config } = useConfigStore()
  function addFile(option: UploadRequestOptions) {
    const {
      file: { name, path }
    } = option
    const hasAddFile = config.files.find((file) => file.path === option.file.path)

    if (hasAddFile) {
      ElMessage({ type: 'info', message: '文件已在列表中' })
    } else {
      config.files.push({ name, path, process: 0, state: VideoState.READY })
    }
    return Promise.resolve()
  }
  async function removeFile(path: string) {
    try {
      await ElMessageBox.confirm('确定要删除吗？')
      const curFile = config.files.find((file) => file.path === path)
      if (curFile && curFile.state === VideoState.COMPRESS) {
        ElMessage({ message: '请等待视频压缩完成', type: 'warning' })
      } else {
        config.files = config.files.filter((file) => file.path !== path)
        ElMessage({ message: '删除成功', type: 'success' })
      }
    } catch (error) {
      ElMessage({ message: '取消删除', type: 'error' })
    }
  }
  async function removeAllFile() {
    try {
      await ElMessageBox.confirm('确定要全部删除吗？')
      config.files = []
      ElMessage({ message: '删除成功', type: 'success' })
    } catch (error) {
      ElMessage({ message: '取消删除', type: 'error' })
    }
  }
  function resetAllVideo() {
    config.files.forEach((file) => {
      file.process = 0
      file.state = VideoState.READY
    })
  }
  return {
    addFile,
    removeFile,
    removeAllFile,
    resetAllVideo
  }
}
